﻿using Microsoft.IdentityModel.Tokens;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Shiloh.Job.Common.Helper
{
    public class JwtHelper
    {
        /// <summary>
        /// 颁发
        /// </summary>
        /// <param name="tokenModel"></param>
        /// <returns></returns>
        public static string IssueJwt(JwtTokenModel tokenModel)
        {
            string issuer = AppsettingHelper.app(["JwtClaims", "Issuer"]);
            string audience = AppsettingHelper.app(["JwtClaims", "Audience"]);
            string secret = AppsettingHelper.app(["JwtClaims", "Secret"]);
            string expireMin = AppsettingHelper.app(["JwtClaims", "ExpireMin"]);
            int _expireMin = 1440;
            int.TryParse(expireMin, out _expireMin);
            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Jti,tokenModel.Uid),
                new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
                new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(_expireMin)).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Iss,issuer),
                new Claim(JwtRegisteredClaimNames.Aud,audience),
            };
            #region 角色Claim
            //单角色
            claims.Add(new Claim(ClaimTypes.Role, tokenModel.Role));
            //多角色使用如下方法
            //claims.AddRange(tokenModel.Role.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));

            #endregion

            ////密钥(SymmetricSecurityKey 对安全性的要求，密钥的长度太短会报出异常)
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwt = new JwtSecurityToken(
                issuer: issuer,
                claims: claims,
                signingCredentials: creds);

            var jwtHandler = new JwtSecurityTokenHandler();
            var encodedJwt = jwtHandler.WriteToken(jwt);

            return encodedJwt;
        }

        /// <summary>
        /// 解析
        /// </summary>
        /// <param name="jwtStr"></param>
        /// <returns></returns>
        public static JwtTokenModel SerializeJwt(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            var canReadToken = jwtHandler.CanReadToken(jwtStr);
            if (canReadToken)
            {
                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
                object role;
                try
                {
                    jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
                var tm = new JwtTokenModel
                {
                    Uid = (jwtToken.Id).ObjToString(),
                    Role = role != null ? role.ObjToString() : "",
                };
                return tm;
            }
            else
                return null;
        }
    }

    public class JwtTokenModel {
        /// <summary>
        /// userid
        /// </summary>
        public string Uid { get; set; }
        /// <summary>
        /// 角色
        /// </summary>
        public string Role { get; set; }
        /// <summary>
        /// 职能
        /// </summary>
        public string Work { get; set; }
    }
}
